class Compiler {
  constructor(vm) {
    this.el = vm.$el;
    this.vm = vm;
  }

  compile(el) {
    let childNodes = el.childNodes;
    Array.from(childNodes).forEach((node) => {
      if (this.isTextNode(node)) {
        this.compileText(node);
      } else if (this.isElementNode(node)) {
        this.compileElement(node);
      }
      if (node.childNodes && node.childNodes.length) {
        this.compile(node);
      }
    });
  }

  compileElement(node) {
    Array.from(node.attributes).forEach((attr) => {
      let attrName = attr.name;
      if (this.isDirective(attrName)) {
        attrName = attrName.substr(2);
        console.log(attrName);
        let key = attr.value;
        this.update(node, key, attrName);
      }
    });
  }

  update(node, key, attrName) {
    if (attrName.indexOf(":") > -1) {
      // 方法
      let eventIdx = attrName.indexOf(":");
      let directiveName = attrName.slice(0, eventIdx);
      let decorateIdx = attrName.indexOf(".", eventIdx) > -1 ? attrName.indexOf(".", eventIdx) : attrName.length;
      let eventName = attrName.slice(eventIdx + 1, decorateIdx);
      let decorates = attrName.slice(decorateIdx).split(".").filter(Boolean);
      let updateFn = this[directiveName + "Updater"];
      updateFn && updateFn.call(this, node, this.vm.$methods[key], key, { eventName, decorates });
    } else {
      // 值
      let updateFn = this[attrName + "Updater"];
      updateFn && updateFn.call(this, node, this.vm[key], key);
    }
  }

  htmlUpdater(node, value, key) {
    node.innerHTML = value;
    new Watcher(this.vm, key, (newValue) => {
      node.innerHTML = newValue;
    });
  }

  // v-on:click.stop.prevent
  onUpdater(node, value, key, data) {
    const eventName = data.eventName;
    const decorates = data.decorates;
    let proxyFn = (e) => {
      console.log("decorates", decorates);
      if (decorates.includes("prevent")) {
        e.preventDefault();
      }
      if (decorates.includes("stop")) {
        e.stopPropagation();
      }
      value && value.call(this.vm, e);
    };
    window.addEventListener(eventName, proxyFn, false);
  }

  // v-text
  textUpdater(node, value, key) {
    node.textContent = value;
    new Watcher(this.vm, key, (newValue) => {
      node.textContent = newValue;
    });
  }

  modelUpdater(node, value, key) {
    node.value = value;
    new Watcher(this.vm, key, (newValue) => {
      node.value = newValue;
    });
  }

  compileText(node) {
    let reg = /\{\{(.+?)\}\}}/;
    let value = node.textContent;
    if (reg.test(value)) {
      let key = RegExp.$1.trim();
      node.textContent = value.replace(reg, this.vm[key]);

      new Watcher(this.vm, key, (newValue) => {
        node.textContent = newValue;
      });
    }
  }

  isDirective(attrName) {
    return attrName.startsWith("v");
  }

  isTextNode(node) {
    return node.nodeType === 3;
  }

  isElementNode(node) {
    return node.nodeType === 1;
  }
}
